<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-left" :style="{ marginTop: safeTop + 'px' }">
				<image src="/static/base/back.svg" class="back-icon" mode="aspectFit" @click="goBack" />
			</view>
			<view class="tab-bar" :style="{ marginTop: heardTop + 'px' }">
				<text :class="['tab-item', activeTab === 'discover' ? 'active' : '']"
					@click="switchTab('discover')">共创</text>
				<text :class="['tab-item', activeTab === 'follow' ? 'active' : '']"
					@click="switchTab('follow')">设计</text>
			</view>
			<view class="header-right">
			</view>
		</view>

		<!-- 搜索框 -->
		<view class="search-bar" :style="{ marginTop: searchTop + 'px' }">
			<view class="search-border">
				<input v-model="searchKeyword" class="search-input" placeholder="输入关键字" @confirm="handleSearchConfirm"
					confirm-type="search" />
				<image src="/static/base/seach.svg" class="search-icon" mode="aspectFit" @click="handleSearch" />
			</view>
		</view>

		<scroll-view scroll-y class="content" @scrolltolower="loadMore">
			<view :style="{height: contentTop + 'px' }"></view>

			<view class="waterfall-container">
				<view class="waterfall-column" v-for="col in columnsData" :key="col.index">
					<view v-for="item in col.items" :key="item.id" class="creative-item"
						@click="goToCreativeDetail(item.id)">
						<view class="image-container" :style="{ height: item.imageHeight + 'rpx' }">
							<image :src="item.coverImage || '/static/base/empty.png'" class="creative-image"
								mode="aspectFill" @load="onImageLoad(item, $event)" />

							<!-- 仅在“设计”页（follow）显示状态标签 -->
							<view v-if="activeTab === 'follow'" class="status-badge"
								:class="item.status === 2 ? 'final' : 'draft'">
								{{ item.statusText }} | {{ item.imageCount }}图
							</view>
						</view>
						<view class="creative-info">
							<text class="creative-title">{{ item.title }}</text>
							<view class="creative-meta">
								<image :src="item.avatar" class="author-avatar" mode="aspectFill" />
								<text class="author-name">{{ item.nickname }}</text>
								<!-- <view class="like-container" @click.stop="toggleLike(item)"> -->
								<view class="like-container">
									<image
										:src="item.liked ? '/static/base/index/good-active.png' : '/static/base/index/good.png'"
										class="like-icon" mode="aspectFit" />
									<text class="like-count" :class="{ active: item.liked }">{{ item.likeNum }}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="load-more" v-if="loading && hasMore">
				<text class="load-text">加载中...</text>
			</view>
			<view class="no-more" v-else-if="!hasMore && creativeWorks.length > 0">
				<text class="no-more-text">没有更多内容了</text>
			</view>
			<view class="no-data" v-else-if="!loading && creativeWorks.length === 0">
				<text class="no-data-text">暂无数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		workLikeAdd,
		workLikeDel,
		getWorkList,
		getDraftList
	} from '@/api/base/index.js'

	export default {
		data() {
			return {
				safeTop: 0,
				heardTop: 0,
				searchTop: 0,
				contentTop: 0,
				activeTab: 'discover',
				searchKeyword: '',
				creativeWorks: [], // 存储后端返回的 item，补充 coverImage、liked、imageHeight
				hasMore: true,
				loading: false,
				currentPage: 1,
				limit: 30,
				columns: 2
			}
		},
		computed: {
			columnsData() {
				const columns = [];
				const colCount = this.columns;
				for (let i = 0; i < colCount; i++) {
					columns.push({
						index: i,
						items: []
					});
				}
				this.creativeWorks.forEach((item, index) => {
					const colIndex = index % colCount;
					columns[colIndex].items.push(item);
				});
				return columns;
			},
			isFollow() {
				return this.activeTab === 'follow' ? 1 : 0;
			}
		},
		onLoad() {
			uni.setNavigationBarTitle({
				title: '共创中心'
			});

			const {
				barTop
			} = this.$util.getWXStatusHeight();
			this.safeTop = barTop;
			this.heardTop = barTop - 5;
			this.searchTop = barTop + 30;
			this.contentTop = barTop + 98;

			this.calculateColumns();
			if (uni.onWindowResize) {
				uni.onWindowResize((res) => {
					this.calculateColumns(res.size.windowWidth);
				});
			}

			this.loadData();
		},
		onUnload() {
			if (uni.offWindowResize) {
				uni.offWindowResize();
			}
		},
		methods: {
			calculateColumns(width = uni.getSystemInfoSync().windowWidth) {
				if (width >= 1200) this.columns = 4;
				else if (width >= 900) this.columns = 3;
				else this.columns = 2;
			},
			// 回车触发
			handleSearchConfirm(e) {
				this.searchKeyword = e.detail.value.trim();
				this.performSearch();
			},

			// 点击搜索图标触发
			handleSearch() {
				this.searchKeyword = this.searchKeyword.trim();
				this.performSearch();
			},
			// 实际执行搜索
			performSearch() {
				this.resetAndLoad();
			},
			goToProfile() {
				uni.navigateTo({
					url: '/pages/index/index'
				});
			},
			goBack() {
				uni.navigateBack();
			},
			goToCreativeDetail(id) {
				const workType = this.activeTab == 'discover' ? 1 : 2
				uni.navigateTo({
					url: `/pages/sub_base/creative-detail/index?id=${id}&workType=${workType}`
				});
			},
			switchTab(tab) {
				if (this.activeTab === tab) return;
				this.activeTab = tab;
				this.resetAndLoad();
			},

			resetAndLoad() {
				this.currentPage = 1;
				this.hasMore = true;
				this.creativeWorks = [];
				this.loadData();
			},
			async loadData() {
				if (this.loading || !this.hasMore) return;
				this.loading = true;

				try {
					let res;
					if (this.activeTab === 'follow') {
						// 调用设计稿列表接口
						res = await getDraftList(this.searchKeyword.trim(), this.currentPage, this.limit);
					} else {
						// 调用共创作品列表接口
						res = await getWorkList(
							this.searchKeyword.trim(),
							this.currentPage,
							this.limit,
							this.isFollow,
							0
						);
					}

					if (res.status === 200) {
						const list = res.data?.list || [];
						const total = res.data?.total || 0;

						// 处理数据：补充 coverImage、liked、imageHeight
						const processedList = list.map(item => {
							let coverImage = '';
							let imageCount = 0;
							if (Array.isArray(item.images) && item.images.length > 0) {
								coverImage = item.images[0];
								imageCount = item.images.length;
							}
							return {
								...item,
								coverImage,
								imageCount, // 👈 新增字段
								statusText: item.status === 2 ? '定稿' : '初稿', // 👈 新增字段
								liked: false,
								imageHeight: 400
							};
						});

						if (this.currentPage === 1) {
							this.creativeWorks = processedList;
						} else {
							this.creativeWorks = [...this.creativeWorks, ...processedList];
						}

						// 判断是否还有更多
						if (this.creativeWorks.length >= total || list.length < this.limit) {
							this.hasMore = false;
						} else {
							this.currentPage++;
						}
					} else {
						uni.showToast({
							title: res.msg || '加载失败',
							icon: 'none'
						});
						this.hasMore = false;
					}
				} catch (error) {
					console.error('加载列表失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
					this.hasMore = false;
				} finally {
					this.loading = false;
				}
			},
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loadData();
				}
			},
			async toggleLike(item) {
				try {
					if (item.liked) {
						await workLikeDel(item.id);
						item.likeNum = Math.max(0, item.likeNum - 1);
					} else {
						await workLikeAdd(item.id);
						item.likeNum += 1;
					}
					item.liked = !item.liked;
				} catch (error) {
					console.error('点赞操作失败:', error);
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			},
			// 动态计算图片高度
			onImageLoad(item, e) {
				const {
					width,
					height
				} = e.detail;
				if (width && height) {
					const screenWidth = uni.getSystemInfoSync().windowWidth;
					const columnWidth = (screenWidth - 2 * 13.88) / this.columns;
					const ratio = height / width;
					item.imageHeight = Math.round(ratio * columnWidth * (750 / screenWidth));
				}
			}
		}
	}
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background-color: #F2F8FC;
	}

	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 27.76rpx;
		z-index: 100;
	}

	.header-left {
		width: 88rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.back-icon {
		width: 44rpx;
		height: 44rpx;
	}

	.tab-bar {
		display: flex;
		gap: 41.64rpx;
	}

	.tab-item {
		font-size: 28rpx;
		color: #666666;
		position: relative;
		margin-top: 4rpx;
	}

	.tab-item.active {
		color: black;
		font-weight: bold;
		font-size: 30rpx;
		margin-top: 0rpx;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: -6.94rpx;
		left: 0;
		right: 0;
		height: 3.47rpx;
		background-color: black;
	}

	.header-right {
		display: flex;
		width: 138.8rpx;
		justify-content: space-between;
	}

	.icon {
		width: 41.64rpx;
		height: 41.64rpx;
	}

	.search-bar {
		position: fixed;
		left: 0;
		right: 0;
		height: 140rpx;
		padding: 40rpx 17rpx 17rpx;
		background-color: #F2F8FC;
		display: flex;
		align-items: center;
		z-index: 99;
	}

	.search-border {
		align-items: center;
		display: flex;
		width: 100%;
		height: 80%;
		background-color: #fff;
	}

	.search-icon {
		width: 41.64rpx;
		height: 41.64rpx;
		color: #999999;
		margin-right: 13.88rpx;
	}

	.search-input {
		flex: 1;
		height: 55.52rpx;
		padding: 0 20.82rpx;
		font-size: 24.29rpx;
	}

	.content {
		height: calc(100vh - 0px);
	}

	.waterfall-container {
		display: flex;
		padding: 13.88rpx;
		gap: 13.88rpx;
		min-width: 100%;
	}

	.waterfall-column {
		display: flex;
		flex-direction: column;
		gap: 13.88rpx;
		flex: 1;
		min-width: 433.75rpx;
	}

	.creative-item {
		background-color: #ffffff;
		overflow: hidden;
	}

	.image-container {
		position: relative;
		width: 100%;
		overflow: hidden;
	}

	.creative-image {
		width: 100%;
		height: 100%;
	}

	/* 左上角状态标签 */
	.status-badge {
		position: absolute;
		top: 10rpx;
		left: 10rpx;
		padding: 8rpx 10rpx;
		border-radius: 8rpx;
		font-size: 22rpx;
		color: white;
		z-index: 2;
	}

	.status-badge.draft {
		background-color: rgba(107, 107, 109, 0.8);
		/* 初稿 */
	}

	.status-badge.final {
		background-color: rgba(107, 107, 109, 0.8);
		/* 定稿 */
	}

	.creative-info {
		padding: 20.82rpx;
	}

	.creative-title {
		font-size: 24.29rpx;
		font-weight: 600;
		color: #333333;
		display: block;
		margin-bottom: 13.88rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.creative-meta {
		display: flex;
		align-items: center;
	}

	.author-avatar {
		width: 34.7rpx;
		height: 34.7rpx;
		border-radius: 17.35rpx;
	}

	.author-name {
		font-size: 20.82rpx;
		color: #666666;
	}

	.like-container {
		display: flex;
		align-items: center;
		gap: 6.94rpx;
		margin-left: auto;
	}

	.like-icon {
		width: 27.76rpx;
		height: 27.76rpx;
	}

	.like-count {
		font-size: 24.29rpx;
		color: #999999;
	}

	.like-count.active {
		color: #ff3366;
	}

	.load-more,
	.no-more {
		text-align: center;
		padding: 34.7rpx;
	}

	.load-text,
	.no-more-text {
		font-size: 24.29rpx;
		color: #999999;
	}

	.no-data {
		text-align: center;
		padding: 60rpx 0;
	}

	.no-data-text {
		font-size: 28rpx;
		color: #999;
	}

	@media (max-width: 768px) {
		.waterfall-column {
			min-width: calc(50% - 4px);
			max-width: calc(50% - 4px);
		}
	}

	@media (min-width: 769px) and (max-width: 1200px) {
		.waterfall-column {
			min-width: calc(33.333% - 5.33px);
			max-width: calc(33.333% - 5.33px);
		}
	}

	@media (min-width: 1201px) {
		.waterfall-column {
			min-width: calc(25% - 6px);
			max-width: calc(25% - 6px);
		}
	}
</style>